<?php

class GoSharkFindGroupForm extends GofishGroupsForm
{
  public function configure()
  {
    $this->setWidgets(array(
      'group_name'               => new sfWidgetFormInputText(),
      'password'        => new sfWidgetFormInputPassword(),
    ));

    $this->widgetSchema['group_name']->setAttribute('onkeyup', "findExistingGroup(this.value)");

    $this->setValidators(array(
      'group_name'        => new sfValidatorString(array('max_length' => 255, 'required' => true)),
      'password'         => new sfValidatorString(array('max_length' => 255, 'required' => true)),
    ));
    
    $this->widgetSchema->setNameFormat("findGroup_form[%s]");
    
    $this->validatorSchema->setPostValidator(
        new sfValidatorCallback(array
            ('callback' => array($this, 'find_group_callback'))));
  }
  
  
  
  protected function doSave($con = null)
  {
 
    return true;
  }
  
    // this function should be in the model !! (it is but doesnt work?)
    public function find_group_callback($validator, $values)
        {
            
            $find_group = Doctrine_Query::create()
                ->from('GofishGroups gg')
                ->where('gg.group_name = ?', $values['group_name'])
                ->count();

            if ($find_group > 1)
            {
                throw new sfValidatorError($validator, "Several groups found, be more specific.");
            }
            if (!$find_group)
            {
                throw new sfValidatorError($validator, "No groups found.");
            }
            
            $check_pass = Doctrine_Query::create()
                ->from('GofishGroups gg')
                ->where('gg.group_name = ?', $values['group_name'])
                ->andWhere('gg.password = ?', $values['password'])
                ->count();
            
            if (!$check_pass)
            {
                throw new sfValidatorError($validator, "Wrong password");
            }
            
            return $values;
        }
        
        
    // BAD, MUST CHANGE: EVERYTHING IS IN CLEAR, USE sfGuardValidatorUser
    public function check_group_password_callback($validator, $values)
        {
            
            $find_group = Doctrine_Query::create()
                ->from('GofishGroups gg')
                ->where('gg.password = ?', $values['password'])
                ->count();

            if ($find_group > 1)
            {
                throw new sfValidatorError($validator, "Several groups found, be more specific.");
            }
            if (!$find_group)
            {
                throw new sfValidatorError($validator, "No groups found.");
            }
            
            return $values;
        }
}

?>